package com.yougong.api.modules.customer.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yougong.api.enums.ErrorEnum;
import com.yougong.api.modules.customer.mapper.CusRoleUserMapper;
import com.yougong.api.modules.customer.model.dto.RoleDto;
import com.yougong.api.modules.customer.model.dto.RoleListDto;
import com.yougong.api.modules.customer.model.enums.RoleEnums;
import com.yougong.api.modules.customer.model.pojo.CusRole;
import com.yougong.api.modules.customer.model.pojo.CusRoleUser;
import com.yougong.api.modules.customer.model.pojo.CusUser;
import com.yougong.api.modules.customer.model.vo.RoleVo;
import com.yougong.api.modules.customer.service.CusRoleService;
import com.yougong.api.modules.customer.mapper.CusRoleMapper;
import com.yougong.api.modules.customer.service.CusRoleUserService;
import com.yougong.api.modules.customer.service.CusUserService;
import com.yougong.common.api.CommonPage;
import com.yougong.common.api.CommonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 001
* @description 针对表【cus_role】的数据库操作Service实现
* @createDate 2022-05-05 16:52:59
*/
@Service
public class CusRoleServiceImpl extends ServiceImpl<CusRoleMapper, CusRole>
    implements CusRoleService{

    @Autowired
    private CusUserService cusUserService;

    @Autowired
    private CusRoleUserService cusRoleUserService;

    @Autowired
    private CusRoleUserMapper cusRoleUserMapper;


    /**
     * 添加用户角色
     *
     * @param roleDto
     * @return
     */
    @Override
    @Transactional
    public CommonResult addRole(RoleDto roleDto) {

        CusUser user = cusUserService.getById(roleDto.getUuid());

        if (user == null){
            return CommonResult.failed(ErrorEnum.NOT_USER);
        }

        if (!RoleEnums.ADMIN.getName().equals(user.getRole())){
            return CommonResult.failed(ErrorEnum.NOT_ADMIN_ID);
        }

        //移除以前的角色
        cusRoleUserService.remove(Wrappers.lambdaQuery(CusRoleUser.class)
                .eq(CusRoleUser::getUserId,user.getUuid()));

        //添加现在的角色
        if (ObjectUtils.isNotEmpty(roleDto.getRoleList())){
            List<CusRoleUser> roleUserList = roleDto.getRoleList().stream().map(
                    role -> {
                        CusRoleUser cusRoleUser = new CusRoleUser();

                        cusRoleUser.setUserId(user.getUuid());
                        cusRoleUser.setRoleId(role);
                        cusRoleUser.setCreatedBy(StpUtil.getLoginId().toString());
                        cusRoleUser.setCreatedTime(LocalDateTime.now());

                        return cusRoleUser;
                    }
            ).collect(Collectors.toList());
            cusRoleUserService.saveBatch(roleUserList);
        }

        return CommonResult.success(null);
    }

    /**
     * 获取管理员
     *
     * @return
     */
    @Override
    public CommonResult<CommonPage<RoleVo>> getManage(RoleListDto roleListDto) {

        Page<CusUser> page = new Page<>(roleListDto.getCurrent(),roleListDto.getPageSize());

        LambdaQueryWrapper<CusUser> wrapper = Wrappers.lambdaQuery(CusUser.class)
                .eq(CusUser::getRole, RoleEnums.ADMIN.getName())
                .like(!StringUtils.isBlank(roleListDto.getUsername()), CusUser::getUsername, roleListDto.getUsername())
                .eq(!ObjectUtils.isEmpty(roleListDto.getStatus()), CusUser::getStatus, roleListDto.getStatus())
                .orderByDesc(CusUser::getCreateDt);

       cusUserService.page(page,wrapper);


        List<RoleVo> roleVoList = new ArrayList<>();

        for (CusUser cusUser : page.getRecords()) {

            if (cusUser.getUuid().equals(StpUtil.getLoginId().toString())) {
                continue;
            }

            RoleVo roleVo = new RoleVo();
            BeanUtils.copyProperties(cusUser, roleVo);
            //查询该用户下所有角色
            List<CusRole> roleList = cusRoleUserMapper.getRole(roleVo.getUuid());

            roleVo.setRoleList(roleList);

            roleVoList.add(roleVo);
        }


        CommonPage<RoleVo> commonPage = new CommonPage<>();

        commonPage.setList(roleVoList);
        commonPage.setTotal(page.getTotal());
        commonPage.setCurrent(roleListDto.getCurrent());
        commonPage.setPageSize(roleListDto.getPageSize());

        return CommonResult.success(commonPage);
    }
}




